package com.qf.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.constant.CommonConstant;
import com.qf.entity.User;
import com.qf.exception.CommonException;
import com.qf.mapper.UserMapper;
import com.qf.entity.param.LoginParam;
import com.qf.service.UserService;
import com.qf.utils.JwtUtils;
import com.qf.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author ljw
 * @version 1.0
 * @Date 2025/1/13 21:43
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;


    @Override
    public String login(LoginParam loginParam) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginParam.getUsername()));
        if(user == null){
            throw new CommonException("用户名错误");
        }
        //针对前端传的数据进行md5
        String md5Pwd = SecureUtil.md5(loginParam.getPassword());

        if (!user.getPassword().equals(md5Pwd)) {
            throw new CommonException(CommonConstant.ERROR, "密码错误");
        }
        //方案二jwt token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", user.getUserId());
        String token = JwtUtils.createJwt(map);
        return token;
    }

    @Override
    public User getInfo(String token) {
        Integer uid = UserUtils.getId();
        return userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserId,uid));
    }
}
